const fs = require("fs");
const path = require("path");
// The zip library needs to be instantiated:
const Zip = new require('node-zip');

const templRender = new require('./tools/templRenderUtil');


var mergeColums = function(page,entityColumns){
	let columns = page.columns;
	for(let pageCol of columns){
		for(let name in entityColumns){
			if(name == pageCol.name){
				pageCol.comment = entityColumns[name].comment;
				if(entityColumns[name].format){
					let formatStr = entityColumns[name].format;
					pageCol.formatName = `${name}_${formatStr.split(":")[1]}`;
				}else{
					pageCol.formatName = name;
				}
			}
		}
	}
}


var generatorFontend = function(zip,entity){
	entity.entityUpName = entity.name.charAt(0).toUpperCase()+entity.name.slice(1);
	entity.entitySubName = entity.name.charAt(0).toLowerCase()+entity.name.slice(1);

	let folder = zip.folder(`app/business/${entity.module}/${entity.name}`);	
	let pages = entity.pages;
	let entityColumn = entity.column;
		for(let page of pages){
				let replaceEntity = {};
				copyField(entity,replaceEntity);
				mergeColums(page,entityColumn);
				replaceEntity.page = page;
				let htmlTempl = "";
				if(page.type=='LIST'&&entity.hasWorkflow){//列表特殊处理
					htmlTempl = fs.readFileSync(pageToFileObj[page.type].wfHtml,{encoding:'utf-8'});
				}else{
					htmlTempl = fs.readFileSync(pageToFileObj[page.type].html,{encoding:'utf-8'});	
				}
				let renderHtmlData = templRender.renderTempl(htmlTempl,replaceEntity);
				folder.file(`${page.name}.html`, renderHtmlData);
				let jsTempl = fs.readFileSync(pageToFileObj[page.type].js,{encoding:'utf-8'});
				let renderJsData = templRender.renderTempl(jsTempl,replaceEntity);
				folder.file(`${page.name}Ctrl.js`, renderJsData);
			}

	let routerTemp = fs.readFileSync(path.join(__dirname,'./templ/fontend/router.js'),{encoding:'utf-8'});
	let routerData = templRender.renderTempl(routerTemp,entity);
	folder.file(`${entity.entitySubName}.router.js`, routerData);		
	let serviceTemp = fs.readFileSync(path.join(__dirname,'./templ/fontend/service.js'),{encoding:'utf-8'});
	let serviceData = templRender.renderTempl(serviceTemp,entity);
	folder.file(`${entity.entitySubName}.service.js`, serviceData);	

	if(entity.hasWorkflow){
		let workflowXmlData = fs.readFileSync(path.join(__dirname,'./templ/workflow/bpmn20.xml'),{encoding:'utf-8'});
		workflowXmlData = templRender.renderTempl(workflowXmlData,entity);
		let workflowZip = new Zip();
		workflowZip.file(`${entity.tableName}_WK.bpmn20.xml`,workflowXmlData);  
		let data = workflowZip.generate({ base64:false, compression: 'DEFLATE' });
    	let wfzipfilePath = path.join(__dirname,'./public/upload/', `${entity.tableName}_WK.zip`);
 		//先写后读
 		fs.writeFileSync(wfzipfilePath, data, 'binary');
 		let wfzipData = fs.readFileSync(wfzipfilePath);	
 		zip.file(`${entity.tableName}_WK.zip`,wfzipData);
		//activityQuickMenu
		let activityQuickMenuXmlData = fs.readFileSync(path.join(__dirname,'./templ/activity.xml'),{encoding:'utf-8'});
		activityQuickMenuXmlData = templRender.renderTempl(activityQuickMenuXmlData,entity);
		zip.folder(`dynaConfig/activitiQuickMenu`).file(`quickMenu-${entity.tableName}.xml`,activityQuickMenuXmlData);  
	}	
	
}

//生成后台代码
var generatorBackend = function(zip,entity){
	entity.entityUpName = entity.name.charAt(0).toUpperCase()+entity.name.slice(1);
	entity.entitySubName = entity.name.charAt(0).toLowerCase()+entity.name.slice(1);
	let entityFile = require('./ramdom/ramdomEntity.js').ramdom(entity);
	let daoFile = require('./ramdom/ramdomDao.js').ramdom(entity);
	let daoImplFile = require('./ramdom/ramdomDaoImpl.js').ramdom(entity);
	let serviceFile = require('./ramdom/ramdomService.js').ramdom(entity);
	let serviceImplFile = require('./ramdom/ramdomServiceImpl.js').ramdom(entity);
	let actionFile = require('./ramdom/ramdomAction.js').ramdom(entity);
	let folder = zip.folder(`cn/conow/${entity.module}`);	
	folder.folder('entity').file(entityFile.fileName, entityFile.data);
	let daoFolder = folder.folder('dao');
	daoFolder.file(daoFile.fileName, daoFile.data);
	daoFolder.file(daoImplFile.fileName, daoImplFile.data);
	let serviceFolder = folder.folder('service');
	serviceFolder.file(serviceFile.fileName, serviceFile.data);
	serviceFolder.file(serviceImplFile.fileName, serviceImplFile.data);
	let actionFolder = folder.folder('action');
	actionFolder.file(actionFile.fileName, actionFile.data);
	//activityQuickMenu
	let listenerData = fs.readFileSync(path.join(__dirname,'./templ/listen.temp'),{encoding:'utf-8'});
	listenerData = listenerData.replace(/\${entity.package}/g,`cn.conow.${entity.module}`);
	listenerData = listenerData.replace(/\${entity.upName}/g,entity.entityUpName);
	listenerData = listenerData.replace(/\${entity.tableName}/g,entity.tableName);
	listenerData = listenerData.replace(/\${entity.author}/g,entity.author);
	listenerData = listenerData.replace(/\${entity.version}/g,entity.version);
	listenerData = listenerData.replace(/\${entity.subName}/g,entity.entitySubName);
	listenerData = templRender.renderTempl(listenerData,entity);
	folder.folder(`listener`).file(`${entity.entityUpName}GlobalListener.java`,listenerData);  
}



//获取zip
module.exports.getZip = function(entity){
	let zip = new Zip();
	//生成后台代码
	generatorBackend(zip,entity);

	//前台代码
	generatorFontend(zip,entity);

	var data = zip.generate({ base64:false, compression: 'DEFLATE' });
	return data;
}

var pageToFileObj = {
	"FORM":{
				html:path.join(__dirname,'./templ/fontend/form.html'),
				js:path.join(__dirname,'./templ/fontend/formCtrl.js')
			},
	"LIST":{
				html:path.join(__dirname,'./templ/fontend/list.html'),
				wfHtml:path.join(__dirname,'./templ/fontend/wfList.html'),
				js:path.join(__dirname,'./templ/fontend/listCtrl.js')
			},
	"DETAIL":{
				html:path.join(__dirname,'./templ/fontend/detail.html'),
				js:path.join(__dirname,'./templ/fontend/detailCtrl.js')
			},
	"APPR":{
				html:path.join(__dirname,'./templ/fontend/appr.html'),
				js:path.join(__dirname,'./templ/fontend/detailCtrl.js')
			}
}


let copyField = function(a,b){
	for(let i in a){
		b[i] = a[i]
	}
}